package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;
//import static org.junit.Assert.fail;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import com.alibaba.fastjson.JSON;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.helipay.util.HeliPayBase;
import com.jh.paymentchannel.pojo.HLRegister;
import com.jh.paymentchannel.util.Util;
import com.jnewsdk.util.SignUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
public class HLPaypageRequest {

    private static final Logger log = LoggerFactory.getLogger(HLPaypageRequest.class);
    @Autowired
    private TopupPayChannelBusiness topupPayChannelBusiness;

//    @Autowired
//    private BranchbankBussiness branchbankBussiness;

    @Autowired
    private Util util;

    private String merchant_no = "C1800001614";

    @Value("${payment.ipAddress}")
    private String ipAddress;

    // 用于请求鉴权绑卡短信接口
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/bksendmessage")
    public @ResponseBody
    Object BindCardSendMessage(@RequestParam(value = "ordercode") String ordercode) {

        Map<String, Object> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");

        String userid = resultObj.getString("userid");
        // 充值卡卡号
        String bankCard = resultObj.getString("bankcard");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("resp_message", "查询银行卡信息有误");
            return map;
        }
        if (resultObj == null) {
            return null;
        }
        String phone = resultObj.getString("phone");

        RestTemplate restTemplate2 = new RestTemplate();
        URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
        String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/sendValidateCode";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("P1_bizType", "QuickPayBindCardValidateCode");
        requestEntity.add("P2_customerNumber", merchant_no);
        requestEntity.add("P3_userId", userid);
        requestEntity.add("P4_orderId", ordercode);
        try {
            requestEntity.add("P5_timestamp", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
        }catch (Exception e){
            log.info("=====DateUtil.getyyyyMMddHHmmssDateFormat(new Date())错误信息：" + e);
        }
        requestEntity.add("P6_cardNo", bankCard);
        requestEntity.add("P7_phone", phone);
        result = restTemplate2.postForObject(url2, requestEntity, String.class);
        return resolveResult(map, result);
    }

    private Map<String, Object> resolveResult(Map<String, Object> map, String result) {
        JSONObject objs = JSONObject.fromObject(result);
        if ("00".equals(objs.getString("code"))) {
            map.put("resp_code", "success");
        } else {
            map.put("resp_code", "failed");
            return map;
        }
        map.put("channel_type", "jf");
        return map;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/quickpaybindcard")
    public @ResponseBody
    Object xjyapipay(
            @RequestParam(value = "ordercode") String ordercode,
            @RequestParam(value = "smsCode") String smsCode,
            @RequestParam(value = "securityCode") String securityCode,
            @RequestParam(value = "expiredTime") String expiredTime) {

        Map<String, String> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");

        String userid = resultObj.getString("userid");
        // 费率
        String rate = resultObj.getString("rate");
        // 充值卡卡号
        String bankCard = resultObj.getString("bankcard");

//        String loginPhone = resultObj.getString("phone");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/userid";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("user_id", userid);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        String respCode;
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            respCode = jsonObject.getString("resp_code");
        } catch (Exception e) {
            log.error("查询结算卡异常" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "无默认结算卡,请绑定默认结算卡");
            return map;
        }

        if (!"000000".equals(respCode)) {
            map.put("resp_code", "failed");
            map.put("channel_type", "sdj");
            map.put("resp_message", "没有结算卡");
            return map;
        }

        // 结算卡卡号
//        String cardNo = resultObj.getString("cardNo");

        String phone = resultObj.getString("phone");

//        String cardType = resultObj.getString("cardType");
        // 银行名称
//        String bankName = resultObj.getString("bankName");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("resp_message", "查询银行卡信息有误");
            return map;
        }
        if (resultObj == null) {
            return null;
        }

        String cardName = resultObj.getString("bankName");

        String cardtype = resultObj.getString("cardType");
        String userName = resultObj.getString("userName");
        // 身份证号
        String idcard = resultObj.getString("idcard");

        String year, month;

        String before = expiredTime.substring(0, 2);
        String after = expiredTime.substring(2, 4);

        BigDecimal big = new BigDecimal(before);
        BigDecimal time = new BigDecimal("12");

        int compareTo = big.compareTo(time);
        // 如果前两位大于12，,代表是年/月的格式
        if (compareTo > 0) {
            year = before;
            month = after;
        } else {
            year = after;
            month = before;
        }

        RestTemplate restTemplate2 = new RestTemplate();
        URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
        String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/bindCard";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("P1_bizType", "SettlementCardBind");
        requestEntity.add("P2_customerNumber", merchant_no);
        requestEntity.add("P3_userId", userid);
        requestEntity.add("P4_orderId", ordercode);
        try {
            requestEntity.add("P5_timestamp", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
        }catch (Exception e){
            log.info("=====DateUtil.getyyyyMMddHHmmssDateFormat(new Date())错误信息：" + e);
        }
        requestEntity.add("P6_payerName", userName);
        requestEntity.add("P7_idCardType", "IDCARD");
        requestEntity.add("P8_idCardNo", idcard);
        requestEntity.add("P9_cardNo", bankCard);
        requestEntity.add("P10_year", year);
        requestEntity.add("P11_month", month);
        requestEntity.add("P12_cvv2", securityCode);
        requestEntity.add("P13_phone", phone);
        requestEntity.add("P14_validateCode", smsCode);
        result = restTemplate2.postForObject(url2, requestEntity, String.class);
        JSONObject objs = JSONObject.fromObject(result);
        if ("绑卡交易成功".equals(objs.getString("message"))) {
            map.put("resp_code", "success");
            map.put("channel_type", "jf");
            map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/cjbindcardsuccess");
            return map;
        } else {
            /*
             * map.put("resp_code", "failed"); map.put(CommonConstants.RESP_MESSAGE,
             * objs.getString("message"));
             */
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/cjbindcarderror");
            return map;
        }

    }

    // 请求绑卡支付短信接口
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/quickpayconsumesms")
    public @ResponseBody
    Object HLPayConsumeSMS(@RequestParam(value = "ordercode") String ordercode) {

        Map<String, Object> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String userid = resultObj.getString("userid");
        // 充值卡卡号
        String bankCard = resultObj.getString("bankcard");

        String amount = resultObj.getString("amount");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/userid";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("user_id", userid);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        String respCode = "";
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            respCode = jsonObject.getString("resp_code");
        } catch (Exception e) {
            log.error("查询结算卡异常" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "无默认结算卡,请绑定默认结算卡");
            return map;
        }

        if (!"000000".equals(respCode)) {
            map.put("resp_code", "failed");
            map.put("channel_type", "sdj");
            map.put("resp_message", "没有结算卡");
            return map;
        }

        // 结算卡卡号
        String cardNo = resultObj.getString("cardNo");
        // 银行名称
        String bankName = resultObj.getString("bankName");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("resp_message", "查询银行卡信息有误");
            return map;
        }
        if (resultObj == null) {
            return null;
        }

        String cardName = resultObj.getString("bankName");

        String cardtype = resultObj.getString("cardType");

        String phone = resultObj.getString("phone");

        HLRegister hlRegisterByXYK = topupPayChannelBusiness.getHLRegisterByBankCardAndCardType(bankCard, "0");
        String bindId = "";
        if (null != hlRegisterByXYK) {
            bindId = hlRegisterByXYK.getBindId();
        }

        RestTemplate restTemplate2 = new RestTemplate();
        URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
        String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/sendPayCode";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("P1_bizType", "QuickPayBindPayValidateCode");
        requestEntity.add("P2_customerNumber", merchant_no);
        requestEntity.add("P3_bindId", bindId);
        requestEntity.add("P4_userId", userid);
        requestEntity.add("P5_orderId", ordercode);
        try {
            requestEntity.add("P6_timestamp", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
        }catch (Exception e){
            log.info("=====DateUtil.getyyyyMMddHHmmssDateFormat(new Date())错误信息：" + e);
        }
        requestEntity.add("P7_currency", "CNY");
        requestEntity.add("P8_orderAmount", amount);
        requestEntity.add("P9_phone", phone);
        result = restTemplate2.postForObject(url2, requestEntity, String.class);
        return resolveResult(map, result);
    }

    // 请求绑卡支付接口
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/quickpayconsume")
    public @ResponseBody
    Object QuickPayConsume(HttpServletRequest request,
                           @RequestParam(value = "ordercode") String ordercode,
                           @RequestParam(value = "smsCode") String smsCode) {

        Map<String, String> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String userid = resultObj.getString("userid");
        // 充值卡卡号
        String bankCard = resultObj.getString("bankcard");

        String amount = resultObj.getString("amount");

        HLRegister hlRegisterByXYK = topupPayChannelBusiness.getHLRegisterByBankCardAndCardType(bankCard, "0");
        String bindId = "";
        if (null != hlRegisterByXYK) {
            bindId = hlRegisterByXYK.getBindId();
        }

        RestTemplate restTemplate2 = new RestTemplate();
        URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
        String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/bindCardPay";
        requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("P1_bizType", "QuickPayBindPay");
        requestEntity.add("P2_customerNumber", merchant_no);
        requestEntity.add("P3_bindId", bindId);
        requestEntity.add("P4_userId", userid);
        requestEntity.add("P5_orderId", ordercode);
        try {
            requestEntity.add("P6_timestamp", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
        }catch (Exception e){
            log.info("=====DateUtil.getyyyyMMddHHmmssDateFormat(new Date())错误信息：" + e);
        }
        requestEntity.add("P7_currency", "CNY");
        requestEntity.add("P8_orderAmount", amount);
        requestEntity.add("P9_goodsName", "充值缴费");
        requestEntity.add("P10_goodsDesc", "充值缴费");
        requestEntity.add("P11_terminalType", "IMEI");
        requestEntity.add("P12_terminalId", "122121212121");
        requestEntity.add("P13_orderIp", request.getLocalAddr());
        requestEntity.add("P14_period", "");
        requestEntity.add("P15_periodUnit", "");
        requestEntity.add("P16_serverCallbackUrl", ipAddress + "/v1.0/paymentchannel/topup/hlpay/notify_call");
        requestEntity.add("P17_validateCode", smsCode);
        result = restTemplate2.postForObject(url2, requestEntity, String.class);
        JSONObject objs = JSONObject.fromObject(result);
        if ("绑卡支付交易成功".equals(objs.getString("message"))) {
            map.put("resp_code", "success");
            map.put("channel_type", "jf");
            map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpaysuccess");
            return map;
        } else {
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpayerror");
            return map;
        }
    }

    // 异步回调接口
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/notify_call")
    public @ResponseBody
    void HLPayNotifyCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> paramMap = SignUtil.parseParam(request);
        JSONObject jsonInfo = JSONObject.fromObject(paramMap);
//        String resString = "fail";
        if ("0000".equals(jsonInfo.getString("rt2_retCode"))) {
            String ordercode = jsonInfo.getString("rt5_orderId");
            String orderstatus = jsonInfo.getString("rt9_orderStatus");
            if ("SUCCESS".equals(orderstatus)) {

                Map<String, Object> map = new HashMap<>();
                RestTemplate restTemplate = new RestTemplate();
                URI uri = util.getServiceUrl("transactionclear", "error url request!");
                String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
                MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("order_code", ordercode);
                String result = restTemplate.postForObject(url, requestEntity, String.class);
                JSONObject jsonObject;
                JSONObject resultObj = null;
                try {
                    jsonObject = JSONObject.fromObject(result);
                    resultObj = jsonObject.getJSONObject("result");
                } catch (Exception e1) {
                    map.put("resp_code", "failed");
                    map.put("channel_type", "jfcoin");
                    map.put("resp_message", "没有该订单信息");
                    log.error(JSON.toJSONString(map));
                }

                String amount = resultObj.getString("amount");
                String userid = resultObj.getString("userid");
                // 费率
                String rate = resultObj.getString("rate");
                // 额外费率
                String extraFee = resultObj.getString("extraFee");

                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/bank/default/userid";
                requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("user_id", userid);
                result = restTemplate.postForObject(url, requestEntity, String.class);
                try {
                    jsonObject = JSONObject.fromObject(result);
                    resultObj = jsonObject.getJSONObject("result");
//                    respCode = jsonObject.getString("resp_code");
                } catch (Exception e) {
                    log.error("查询结算卡异常" + e.getMessage());
                    map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                    map.put(CommonConstants.RESP_MESSAGE, "无默认结算卡,请绑定默认结算卡");
                    log.error(JSON.toJSONString(map));
                }

                // 结算卡卡号
                String cardNo = resultObj.getString("cardNo");

                BigDecimal bigamount = new BigDecimal(amount);
                BigDecimal bigrate = new BigDecimal(rate);
                BigDecimal bigextraFee = new BigDecimal(extraFee);

                //订单总金额乘以费率的值
                BigDecimal multiply = bigamount.multiply(bigrate);
                //订单总金额减去 订单总金额乘以费率的值
                BigDecimal subtract = bigamount.subtract(multiply);
                //再减去额外费用
                BigDecimal Amount = subtract.subtract(bigextraFee);

                BigDecimal setScale = Amount.setScale(2, RoundingMode.CEILING);

                HLRegister hlRegisterByJSK = topupPayChannelBusiness.getHLRegisterByBankCardAndCardType(cardNo, "2");
                String bindId = "";
                if (null != hlRegisterByJSK) {
                    bindId = hlRegisterByJSK.getBindId();
                }

                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("paymentchannel", "error url request!");
                url = uri.toString() + "/v1.0/paymentchannel/topup/settlementCardWithdraw";
                requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("P1_bizType", "SettlementCardWithdraw");
                requestEntity.add("P2_customerNumber", HeliPayBase.MERCHANT_NO);
                requestEntity.add("P3_userId", userid);
                requestEntity.add("P4_orderId", ordercode);
                requestEntity.add("P5_amount", setScale + "");
                requestEntity.add("P6_feeType", "PAYER");
                requestEntity.add("P7_summary", "");
                requestEntity.add("P8_bindId", bindId);
                result = restTemplate.postForObject(url, requestEntity, String.class);
                jsonObject = JSONObject.fromObject(result);
                if ("结算卡提现成功".equals(jsonObject.getString("message"))) {
                    uri = util.getServiceUrl("paymentchannel", "error url request!");
                    url = uri.toString() + "/v1.0/paymentchannel/topup/queryOrder";
                    requestEntity = new LinkedMultiValueMap<>();
                    requestEntity.add("P1_bizType", "TransferQuery");
                    requestEntity.add("P2_orderId", ordercode);
                    requestEntity.add("P3_customerNumber", HeliPayBase.MERCHANT_NO);
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    jsonObject = JSONObject.fromObject(result);
                    if ("订单查询成功".equals(jsonObject.getString("message"))) {
                        JSONObject jsonObj = jsonObject.getJSONObject("json");
                        if ("0000".equals(jsonObj.getString("rt2_retCode"))) {
                            if (jsonObj.containsKey("rt7_orderStatus")) {
                                /*
                                 * INIT已接收 DOING处理中 SUCCESS成功 FAIL失败
                                 * REFUND退款
                                 */

                                if ("INIT".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
                                        || "DOING".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
                                        || "SUCCESS".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {

                                    restTemplate = new RestTemplate();
                                    uri = util.getServiceUrl("transactionclear", "error url request!");
                                    url = uri.toString() + "/v1.0/transactionclear/payment/update";
                                    requestEntity = new LinkedMultiValueMap<>();
                                    requestEntity.add("status", "1");
                                    requestEntity.add("order_code", ordercode);
                                    result = restTemplate.postForObject(url, requestEntity, String.class);
                                    log.info("TransactionClear/TaiwanCardOrder/Update result: {}", result);

                                    PrintWriter write = response.getWriter();
                                    write.print("success");
                                    write.flush();

                                } else {
                                    // 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
                                    // 2、返回响应内容
                                    log.trace("订单支付失败!");
                                    PrintWriter write = response.getWriter();
                                    write.print("failure");
                                    write.flush();
                                }
                            }
                        }
                    }
                }
            }
        }

    }


    //跳转到绑卡页面的中转接口
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/turntobindcardpage")
    public @ResponseBody
    Object TurnToBindCardPage(
            @RequestParam(value = "ordercode") String ordercode,
            @RequestParam(value = "securityCode") String securityCode,
            @RequestParam(value = "expiredTime") String expiredTime,
            @RequestParam(value = "cardName") String cardName,
            @RequestParam(value = "bankCard") String bankCard,
            @RequestParam(value = "cardtype") String cardtype

    ) throws IOException {

        Map<String, Object> map = new HashMap<>();

        map.put("resp_code", "success");
        map.put("channel_type", "jf");
        map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybindcard?&ordercode=" +
                ordercode + "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&cardName=" +
                URLEncoder.encode(cardName, "UTF-8") + "&bankCard=" + bankCard + "&cardtype=" + cardtype);
        return map;

    }


    //跳转到支付页面的中转接口
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/hlpay/turntopaypage")
    public @ResponseBody
    Object TurnToPayPage(@RequestParam(value = "ordercode") String ordercode) {

        Map<String, Object> map = new HashMap<>();
        map.put("resp_code", "success");
        map.put("channel_type", "jf");
        map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaypay?&ordercode=" + ordercode);
        return map;

    }


    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tohlpaypay")
    public String toHLPayPay(HttpServletRequest request, HttpServletResponse response, Model model)
            throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String ordercode = request.getParameter("ordercode");

        model.addAttribute("ordercode", ordercode);

        return "hlpaymessage";
    }


    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tohlpaybindcard")
    public String toHLPayBindCard(HttpServletRequest request, HttpServletResponse response, Model model)
            throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String ordercode = request.getParameter("ordercode");
        String securityCode = request.getParameter("securityCode");
        String expiredTime = request.getParameter("expiredTime");
        String cardName = request.getParameter("cardName");
        String bankCard = request.getParameter("bankCard");
        String cardtype = request.getParameter("cardtype");

        model.addAttribute("ordercode", ordercode);
        model.addAttribute("securityCode", securityCode);
        model.addAttribute("expiredTime", expiredTime);
        model.addAttribute("cardName", cardName);
        model.addAttribute("bankCard", bankCard);
        model.addAttribute("cardtype", cardtype);

        return "hlpaybindcard";
    }


    // 跳转到确认银行信息的页面
    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tohlpaybankinfo")
    public String toHLPayBankInfo(HttpServletRequest request, HttpServletResponse response, Model model)
            throws IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String bankName = request.getParameter("bankName");// 结算卡银行名称
        String bankNo = request.getParameter("bankNo");// 结算卡卡号
        String amount = request.getParameter("amount");
        String ordercode = request.getParameter("ordercode");
        String cardType = request.getParameter("cardType");// 结算卡的cardType
        String ipAddress = request.getParameter("ipAddress");
        String cardName = request.getParameter("cardName");// 信用卡银行名称
        String bankCard = request.getParameter("bankCard");// 信用卡卡号
        String cardtype = request.getParameter("cardtype");// 信用卡的cardType
        String securityCode = request.getParameter("securityCode");
        String expiredTime = request.getParameter("expiredTime");
        String isBindCard = request.getParameter("isBindCard");

        model.addAttribute("bankName", bankName);
        model.addAttribute("bankNo", bankNo);
        model.addAttribute("amount", amount);
        model.addAttribute("ordercode", ordercode);
        model.addAttribute("cardType", cardType);
        model.addAttribute("ipAddress", ipAddress);
        model.addAttribute("cardName", cardName);
        model.addAttribute("bankCard", bankCard);
        model.addAttribute("cardtype", cardtype);
        model.addAttribute("securityCode", securityCode);
        model.addAttribute("expiredTime", expiredTime);
        model.addAttribute("isBindCard", isBindCard);

        return "hlpaybankinfo";
    }

}